package com.chen.blog.config.security.component;

import com.chen.blog.common.api.CommonResult;
import com.chen.blog.common.constant.MessageConstant;
import com.chen.blog.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description 通用认证操作
 * @Author zgyh2
 * @Date 2022/1/24
 * @Version 1.0
 */
@Component
public class AuthenticationUtil {

    @Autowired
    private RedisTemplate redisTemplate;

    @Lazy
    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    @Lazy
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    /**
     * 登陆操作
     *
     * @param loginVo
     * @return
     */
    public CommonResult login(LoginVo loginVo) {
        //登录逻辑
        String captcha = (String) redisTemplate.opsForValue().get("code");
        if (StringUtils.isEmpty(loginVo.getCode()) || !captcha.equalsIgnoreCase(loginVo.getCode())) {
            return CommonResult.error(MessageConstant.CODE_FAIL);
        }
        UserDetails userDetails = userDetailsService.loadUserByUsername(loginVo.getUsername());
        if (null == userDetails || !passwordEncoder.matches(loginVo.getPassword(), userDetails.getPassword())) {
            return CommonResult.error(MessageConstant.ADMIN_LOGIN_FAIL);
        }
        if (!userDetails.isEnabled()) {
            return CommonResult.error(MessageConstant.USER_NAME_FAIL);
        }
        //更新security登录用户对象
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                userDetails, null, null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //生成token
        Map<String, Object> tokenMap = new HashMap<>();
        tokenMap.put("token", jwtTokenUtil.generateToken(userDetails));
        tokenMap.put("tokenHead", tokenHead);
        return CommonResult.success(MessageConstant.ADMIN_LOGIN_SUCCESS, tokenMap);
    }

}
